package com.wang.controller;


import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUnit;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.poi.excel.ExcelUtil;
import cn.hutool.poi.excel.ExcelWriter;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.wang.common.Result;
import com.wang.entity.Book;
import com.wang.entity.User;
import com.wang.mapper.BookMapper;
import com.wang.mapper.UserMapper;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;


@RestController
@RequestMapping("/book")
public class BookController {
    @Resource
    BookMapper BookMapper;



    @PostMapping
    public Result<?> save(@RequestBody Book Book){
        BookMapper.insert(Book);
        return Result.success();
    }

    @PostMapping("/deleteBatch")
    public Result<?> deleteBatch(@RequestBody List<Integer> ids){
        BookMapper.deleteBatchIds(ids);
        return Result.success();
    }

    @GetMapping
    public Result<?> findPage(@RequestParam(defaultValue ="1" ) Integer pageNum,
                              @RequestParam(defaultValue = "10") Integer pageSize,
                              @RequestParam(defaultValue = "") String search){
        LambdaQueryWrapper<Book> wrapper = Wrappers.<Book>lambdaQuery();
        if (StrUtil.isNotBlank(search)){
            wrapper.like(Book::getName, search);
        }
        Page<Book> BookPage=BookMapper.selectPage(new Page<>(pageNum,pageSize),wrapper );
        return Result.success(BookPage);

    }

    @PutMapping
    public Result<?> update(@RequestBody Book Book){
       BookMapper.updateById(Book);
        return Result.success();

    }

    @GetMapping("/{id}")
    public Result<?> getById(@PathVariable Long id){
        return Result.success(BookMapper.selectById(id));
    }


    @DeleteMapping("/{id}")
    public Result<?> delete(@PathVariable Long id){
        BookMapper.deleteById(id);
        return Result.success();

    }
    /**
     * Excel导出
     * @param response
     * @throws IOException
     */
    @GetMapping("/export")
    public void export(HttpServletResponse response) throws IOException {

        List<Map<String, Object>> list = CollUtil.newArrayList();

        List<Book> all = BookMapper.selectList(null);
        for (Book book : all) {
            Map<String, Object> row1 = new LinkedHashMap<>();
            row1.put("名称", book.getName());
            row1.put("价格", book.getPrice());
            row1.put("作者", book.getAuthor());
            row1.put("出版日期", book.getCreateTime());
            row1.put("封面", book.getCover());
            list.add(row1);
        }

        // 2. 写excel
        ExcelWriter writer = ExcelUtil.getWriter(true);
        writer.write(list, true);

        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8");
        String fileName = URLEncoder.encode("书籍信息", "UTF-8");
        response.setHeader("Content-Disposition", "attachment;filename=" + fileName + ".xlsx");

        ServletOutputStream out = response.getOutputStream();
        writer.flush(out, true);
        writer.close();
        IoUtil.close(System.out);
    }
    /**
     * Excel导入
     * 导入的模板可以使用 Excel导出的文件
     * @param file Excel
     * @return
     * @throws IOException
     */
    @PostMapping("/import")
    public Result<?> upload(MultipartFile file) throws IOException {
        InputStream inputStream = file.getInputStream();
        List<List<Object>> lists = ExcelUtil.getReader(inputStream).read(1);
        List<Book> saveList = new ArrayList<>();
        for (List<Object> row : lists) {
            Book book = new Book();
            book.setName(row.get(0).toString());
            book.setPrice((BigDecimal) row.get(1));
            book.setAuthor(row.get(2).toString());
            book.setCreateTime(DateUtil.parse(row.get(3).toString(), "yyyy-MM-dd"));
            book.setCover(row.get(4).toString());

            saveList.add(book);
        }
        for (Book book: saveList) {
            BookMapper.insert(book);
        }
        return Result.success();
    }


}
